﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;
using Models;
using DbControl;
using System.Configuration;
using System.Xml.Linq;

namespace CentralMonitoring
{
    /// <summary>
    /// 设备信息管理窗体
    /// </summary>
    public partial class DeviceOverviewFrm : Form
    {
        public DeviceOverviewFrm()
        {
            InitializeComponent();
        }       
        private bool m_isParent = false;
        #region treeview
        private void InitTree()
        {
            this.treeView1.Nodes.Clear();
            DataTable dt = OprDevice.GetdevicesTree(); 
            if (dt != null && dt.Rows.Count > 0)
            {
                DataView dv = dt.DefaultView;
                dv.Sort = "parentid ASC";
                DataRowView[] arrDRV = dv.FindRows("0");
                if (arrDRV.Length == 0)
                    return;
                TreeNode tnNew = null;
                treeView1.BeginUpdate();
                foreach (DataRowView drv in arrDRV)
                {
                    tnNew = this.treeView1.Nodes.Add(drv["device_name"].ToString());
                    tnNew.Tag = drv.Row["id"];
                    CreateTreeNode(ref tnNew, dv);
                }
                treeView1.EndUpdate();
                treeView1.ExpandAll();
            }
        }
        private void CreateTreeNode(ref TreeNode tnParent, DataView dv)
        {
            DataRowView[] arrDrv = dv.FindRows(tnParent.Tag);
            if (arrDrv.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDrv)
            {
                tnNew = tnParent.Nodes.Add(drv.Row["device_name"].ToString());
                tnNew.Tag = drv.Row["ID"].ToString();
                CreateTreeNode(ref tnNew, dv);

            }
        }
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode currentNode = treeView1.GetNodeAt(clickPoint);
                if (currentNode != null)
                {                   
                    treeView1.SelectedNode = currentNode;
                }
                else
                {                   
                    treeView1.SelectedNode = null;
                }
            }

        }
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int nodeId;
            if (e.Node.Nodes.Count > 0)
            {
                e.Node.Expand();                
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid(nodeId,true);
                m_isParent = true;
            }
            else
            {
                nodeId=int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid(nodeId, false);
            }           
        }   
        
        #endregion
        private void SensorsConfigFrm_Load(object sender, EventArgs e)
        {
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));            
            this.WindowState = FormWindowState.Maximized;
            InitTree();
            RefreshGrid("");
        }

        private void RefreshGrid(int parentid, bool isParent = false)
        {
            DataTable dataTable = new DataTable();
            dataTable = OprUI.GetDeevicesView(parentid, isParent);
            RefreshGrid(dataTable);
        }
        private void RefreshGrid(string name)
        {
            DataTable dt = OprUI.GetDeevicesView(name);
            if (dt != null)
            {
                RefreshGrid(dt);
            }

        }
        private void RefreshGrid(DataTable dt)
        {
            flowLayoutPanel1.Controls.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    DeviceControl deviceControl = new DeviceControl();
                    deviceControl.Name = row["device_code"].ToString();
                    deviceControl.mParaDvName = row["device_name"].ToString();
                    deviceControl.mParaDvOil.Text = row["oil_name"].ToString();
                    deviceControl.mParaDvSensor.Text = row["sensor_name"].ToString();
                    if (!(row["device_position"] is DBNull))
                        deviceControl.mParaDvSite.Text = row["device_position"].ToString();
                    deviceControl.mParaView.Tag = row["device_code"].ToString();
                    if (row["install_time"] is DateTime)
                    {
                        TimeSpan timespan = DateTime.Now - (DateTime)row["install_time"];
                        deviceControl.mParaDvTime.Text = timespan.Days.ToString()+"天";
                    }
                    if (row["online_status"] is int)
                    {
                        deviceControl.SetLight((int)row["online_status"]);
                    }
                    deviceControl.mParaView.Click += MParaView_Click;
                    flowLayoutPanel1.Controls.Add(deviceControl);
                }
                flowLayoutPanel1.AutoScroll = true;
            }
        }

        private void MParaView_Click(object sender, EventArgs e)
        {
            //MessageBox.Show((sender as Button).Tag.ToString());
            string code = (sender as Button).Tag.ToString();
            Devicelist devicelist = session.m_dvList.Find(t => t.devCode == code);
            if (devicelist != null)
            {
                if (MainFrm.monitorFrm == null)
                {
                    MainFrm.monitorFrm = new MonitorFrm();
                }
                MainFrm.monitorFrm.ReLoadUI(code);
                MainFrm.monitorFrm.Show();
            }
            else
            {               
                MessageBox.Show("此设备暂没有绑定终端，无监测数据可查，请绑定后重试!!!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
            
        }

        private void buttonFind_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxDevice.Text))
            {
                RefreshGrid(textBoxDevice.Text);
            }
              
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            ServerEdit dlg=new ServerEdit();
            dlg.ShowDialog();
        }
        private void buttonWarnSet_Click(object sender, EventArgs e)
        {

        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
